<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="12">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.payrollMonth"
              mode="month"
              :placeholder="['发放月份', '发放月份']"
            />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="openEdit('新增')">新增</AButton>
        </ASpace>
        <ASpace>
          <!-- <AButton type="primary" @click="onExport('table')">导出</AButton> -->
        </ASpace>
      </div>
      <ATable
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :span-method="spanMethod"
        column-resizable
        size="small"
      >
        <template #columns>
          <ATableColumn title="发放月份" data-index="payrollMonth" :width="160">
            <template #cell="{ record }">
              {{ dayjs(record.payrollMonth).format('YYYY-MM') }}
            </template>
          </ATableColumn>
          <ATableColumn title="人员数量" data-index="numberOfEmployee" :width="160"> </ATableColumn>
          <ATableColumn title="已发数量" data-index="givedCount" :width="150"> </ATableColumn>
          <ATableColumn title="未发数量" data-index="ungiveCount" :width="120" align="center">
          </ATableColumn>
          <ATableColumn
            v-if="isAuth([1, 3])"
            title="操作"
            :width="145"
            align="center"
            fixed="right"
          >
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'detail')">
                  查看详情
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
  </div>
  <AModal
    v-model:visible="editModal"
    title="新增"
    width="300px"
    @close="modalEvent('close')"
    @ok="modalEvent('ok')"
    @open="modalEvent('open')"
    @cancel="modalEvent('cancel')"
  >
    <AMonthPicker
      v-model="formData.payrollMonth"
      placeholder="请选择工资单月份"
      class="w100"
      :allow-clear="false"
    ></AMonthPicker>
  </AModal>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { Message, Modal } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  delSalarySheetList,
  editSalarySheetList,
  // getSalarySheetListAllList,
  getSalarySheetListPageList,
  SalarySheetReq,
  SalarySheetResItem,
  SalarySheetSearch
} from '@renderer/api/salarySheet'
import { useMenuState } from '@renderer/store'

const emit = defineEmits(['switch'])
const searchFrom = ref<SalarySheetSearch>({
  payrollMonth: []
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<SalarySheetResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const formData = ref<SalarySheetReq>({
  payrollMonth: dayjs().format('YYYY-MM')
})
const menuParam = useMenuState()

onMounted(() => {
  getTableData()
})

async function getTableData() {
  const [StartMonth, EndMonth] = searchFrom.value.payrollMonth || []
  searchFrom.value.payrollStartMonth = StartMonth ? dayjs(StartMonth).format('YYYY-MM') : ''
  searchFrom.value.payrollEndMonth = EndMonth ? dayjs(EndMonth).format('YYYY-MM') : ''
  const res = await getSalarySheetListPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {
    payrollMonth: []
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}
const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 2) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

function modalEvent(type: string) {
  switch (type) {
    case 'ok':
      if (!formData.value.payrollMonth) {
        Message.warning('请选择发放月份')
        return
      }
      editSalarySheetList(formData.value).then(() => {
        Message.success('新增成功')
        modalEvent('cancel')
        getTableData()
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      editModal.value = false
      formData.value.payrollMonth = dayjs().format('YYYY-MM')
      break
    case 'open':
      menuParam.switchEditStatus(true)
      break
    case 'cancel':
      editModal.value = false
      formData.value.payrollMonth = dayjs().format('YYYY-MM')
      menuParam.switchEditStatus(false)
      break
    default:
      break
  }
}

const rowData = ref({})
function rowEvent(row: SalarySheetResItem, type: 'del' | 'detail') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delSalarySheetList({ payrollId: row.payrollId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'detail':
      emit('switch', row)
      break

    default:
      break
  }
}

// async function onExport(type: 'table' | 'template') {
//   let fileTitle: string
//   const headerData = [
//     { title: '报价单号', value: 'quotationOrderCode', width: 180 },
//     { title: '客户名称', value: 'customerName' },
//     { title: '产品名称', value: 'productName' },
//     { title: '规格', value: 'specModel' },
//     { title: '型号', value: 'spec' },
//     { title: '类别', value: 'materialCategory' },
//     { title: '材质代码', value: 'materialCode' },
//     { title: '纸箱规格', value: 'cartonSpec' },
//     { title: '单价', value: 'unitPrice' },
//     { title: '含税', value: 'isInclTax' },
//     { title: '送货方式', value: 'deliveryMethod' },
//     { title: '结算方式', value: 'paymentMethod' },
//     { title: '备注', value: 'remark' },
//     { title: '创建人', value: 'createdBy' }
//   ]
//   let excelData: any[] = []
//   switch (type) {
//     case 'table':
//       {
//         fileTitle = '工资单数据'
//         const res = await getSalarySheetListAllList(searchFrom)
//         excelData = res.data.list
//       }
//       break
//     case 'template':
//       fileTitle = '工资单导入模板'
//       excelData = [
//         {
//           quotationOrderCode: '1883026226361159682',
//           customerName: '湘巧食品有限公司',
//           productName: '夹心巧克力',
//           specModel: 0,
//           spec: '包送',
//           materialCategory: '现结',
//           materialCode: '测试',
//           cartonSpec: '',
//           unitPrice: '10',
//           isInclTax: '是',
//           deliveryMethod: '包送',
//           paymentMethod: '现结',
//           remark: '',
//           createdBy: 'test/模拟用户'
//         }
//       ]
//       break
//     default:
//       break
//   }
//   import('@renderer/utils/vendor').then((excel) => {
//     excel.exportExcel(excelData, headerData, fileTitle)
//   })
// }
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
